from google.appengine.ext import db
from lib.models import Grade
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
import os
from google.appengine.api import memcache
from google.appengine.api import users

def count_grades(results):
    counts = []
    for i in range(11):
        counts.append([i,0])

    fails = 0
    successes =0
    for result in results :
        counts[int(result.grade)][1]= counts[int(result.grade)][1]+1
        if int(result.grade)<5:
            fails = fails+1
        else:
            successes= successes + 1

    return {"counts":counts, "fails":fails, "successes":successes}





class MainPage(webapp.RequestHandler):
    def get(self):

        cid = self.request.get('cid')
        ref = "none"
        ref = self.request.get('ref')

        use_cache = "yes"
        use_cache = self.request.get('use_cache')
       
        page = memcache.get("-".join([cid,ref]))

        user = users.get_current_user()
        if user:
            if users.is_current_user_admin() and use_cache=="no":
                page=None

        if page is None:
            query = Grade.all().filter("cid =", cid)
            counts = count_grades(query)
            title = query[0].course_name
            template_values = {
                    "title":title,
                    "results":query,
                    "statistics":counts,
                    }
            path = os.path.join(os.path.dirname(__file__), '../templates/course.html')
            page = template.render(path,template_values)
            memcache.add("-".join([cid,ref]), page, 86400)
        self.response.out.write(page)




application = webapp.WSGIApplication(
                                     [('/course', MainPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main() 
